﻿Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_TiepNhan_CapDoi
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            hidCurHuyenId.Value = Session("HuyenId")
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            DivChanging.Visible = False
            DivBussiness.Visible = False
            ThongBao.Visible = False
            If Not Request("CertifiedId") Is Nothing AndAlso Request("CertifiedId") <> 0 Then
                hidID.Value = Request("CertifiedId")

                'DivChanging.Visible = False
                DivBussiness.Visible = True
                Bind2Gid()
                Load2Grid(hidID.Value)
            End If
        End If
    End Sub
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Using _data As New VSEntities
            'lay username
            Dim _u As String = Session("UserName")
            'Dim p = (From q In _data.CertifiedHouseholds Where (q.CertifiedCode = txtGiayChungNhan.Text Or q.Ow_CardID = txtGiayChungNhan.Text) And q.StatusId = TinhTrangHoSo.Hoantat Order By q.CertifiedUp_Time Descending Select q).FirstOrDefault
            Dim p = (From q In _data.CertifiedHouseholds Where (q.CertifiedCode = txtGiayChungNhan.Text.Trim() Or q.Ow_CardID = txtGiayChungNhan.Text.Trim()) _
                                            And q.ProvinceId = hidCurHuyenId.Value _
                                            And q.CertifiedCode <> ""
                                            Order By q.CertifiedDate Descending Select q).FirstOrDefault
            If Not p Is Nothing Then
                ' Bind2Gid()
                '  Load2Grid(_CertifiedId)
                Response.Redirect(MainDomain & "Page/TiepNhan/CapDoi.aspx?CertifiedId=" & p.CertifiedID)
                ' Session("GiayCapDoi") = _CertifiedId
            Else
                '  Session("GiayCapDoi") = Nothing
                hplCapMoi.NavigateUrl = MainDomain & "Page/TiepNhan/CapMoi.aspx"
                DivChanging.Visible = False
                DivBussiness.Visible = False
                ThongBao.Visible = True
                'Response.Redirect(MainDomain & "Page/TiepNhan/CapDoi.aspx?CertifiedId=")

            End If
        End Using
    End Sub
    Protected Sub Bind2Gid()
        Using _data As New VSEntities

            'loai thay doi
            Dim lstLoaiThayDoi = (From q In _data.ChangingTypes Order By q.Name Select q).ToList
            DivChanging.Visible = True
            Dim strKey_Name() As String = {"Id", "Code", "Name"}
            With grdShowLoaiThayDoi
                .DataKeyNames = strKey_Name
                .DataSource = lstLoaiThayDoi
                .DataBind()
            End With

        End Using
    End Sub
    Protected Sub Load2Grid(ByVal _h As Integer)
        Using _data As New VSEntities
            'provinces 
            Dim _tinhthanh = (From q In _data.Provinces Where q.ParentId = 0 Order By q.Title Select q.Id, q.Code, q.Title).ToList

            With ddlTinhDiaDiemKD
                .DataSource = _tinhthanh
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Add(New ListItem("--- Chọn ---", 0))
                .SelectedValue = 0
            End With

            With ddlTinhHoKhau
                .DataSource = _tinhthanh
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Add(New ListItem("--- Chọn ---", 0))
                .SelectedValue = 0
            End With

            ''tam tru

            With ddlTinhHienTai
                .DataSource = _tinhthanh
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Add(New ListItem("--- Chọn ---", 0))
                .SelectedValue = 0
            End With

            'NGanh nghe
            Dim linhvuc = (From q In _data.BusinessFields Order By q.Name Select New With {.Id = q.Id, .Name = q.Name}).ToList
            With ddlBusinessField
                .DataSource = linhvuc
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Add(New ListItem("--- Chọn ---", 0))
                .SelectedValue = 0
            End With

            ''dan toc
            Dim dantoc = (From q In _data.Citizens Order By q.Name Select New With {.Id = q.Name, .Name = q.Name}).ToList
            With ddlCitizen
                .DataSource = dantoc
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Add(New ListItem("--- Chọn ---", 0))
                .SelectedValue = 0
            End With

            'quoc gia
            Dim Country = (From q In _data.Countries Order By q.Name Select New With {.Id = q.Name, .Name = q.Name}).ToList
            With ddlCountry
                .DataSource = Country
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Add(New ListItem("--- Chọn ---", 0))
                .SelectedValue = 0
            End With

            'dong vi cap giay chung nhan CMND
            Dim DeptCertified = (From q In _data.DeptIdentifies Order By q.Name Select New With {.Id = q.Name, .Name = q.Name}).ToList
            With ddlDeptCertified
                .DataSource = DeptCertified
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Add(New ListItem("--- Chọn ---", 0))
                .SelectedValue = 0
            End With

            ' 'don vi cap giay khac
            Dim d = (From q In _data.DeptIdentifies Order By q.Name Select New With {.Id = q.Name, .Name = q.Name}).ToList
            With ddlOthersPaper_NoiCap
                .DataSource = d
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Add(New ListItem("--- Chọn ---", 0))
                .SelectedValue = 0
            End With

            'giấy tờ khác
            Dim CertifiedPaperDict = (From q In _data.CertifiedPaperDicts Order By q.Name Select New With {.Id = q.Name, .Name = q.Name}).ToList
            With ddlOthersPaper
                .DataSource = CertifiedPaperDict
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Add(New ListItem("--- Chọn ---", 0))
                .SelectedValue = 0
            End With
            'thanh phan ho so
            Dim lstThanhPhanHoSo = (From q In _data.ThanhPhanHoSoes Order By q.IsDefault Descending, q.TenHoSo Select q).ToList
            Dim strKey_Name() As String = {"Id", "MaHoSo", "IsDefault"}
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = lstThanhPhanHoSo
                .DataBind()
            End With
            Dim p = (From q In _data.CertifiedHouseholds Where q.CertifiedID = _h Select q).FirstOrDefault

            If Not p Is Nothing Then
                'check status neu la 4 moi hien nut send
                'If p.StatusId <> TinhTrangHoSo.Hoantat Then
                '    btnSend.Visible = False
                'End If
                'test
                If p.StatusId <> TinhTrangHoSo.Nhap Then
                    btnSave.Visible = True
                End If
                'thong tin ca nhan
                txtOwRepresentative.Text = IIf(IsNothing(p.Ow_Name) = True, "", p.Ow_Name) 'Họ tên
                rdlSex.SelectedValue = IIf(IsNothing(p.Ow_Sex) = True, "", p.Ow_Sex) 'giới tính
                txtOwDateOfBirth.Text = IIf(IsNothing(p.Ow_BirthDate) = True, "", p.Ow_BirthDate) 'ngày tháng năm sinh

                Dim National = p.Ow_National_ID
                If IsNumeric(National) Then 'kiểm tra number hay string
                    If Not p.Ow_National_ID Is Nothing AndAlso p.Ow_National_ID <> "" Then
                        ddlCitizen.SelectedValue = p.Ow_National_ID
                    End If

                Else
                    Dim _joinNational = (From k In _data.Citizens Where k.Name = National Select k).FirstOrDefault
                    If Not _joinNational Is Nothing Then
                        ddlCitizen.SelectedValue = _joinNational.Name
                    End If

                End If

                'Quốc tịch
                'trường hợp dữ liệu inport vào trường Quốc tịch là chuỗi
                Dim Nationality = p.Ow_Nationality_ID
                If IsNumeric(Nationality) Then 'kiểm tra number hay string
                    If Not p.Ow_Nationality_ID Is Nothing AndAlso p.Ow_Nationality_ID <> "" Then
                        ddlCountry.SelectedValue = p.Ow_Nationality_ID
                    End If
                Else
                    Dim _joinNationality = (From k In _data.Countries Where k.Name = Nationality Select k).FirstOrDefault
                    If Not _joinNationality Is Nothing Then
                        ddlCountry.SelectedValue = _joinNationality.Name
                    End If

                End If

                txtOwCardId.Text = IIf(IsNothing(p.Ow_CardID) = True, "", p.Ow_CardID) 'Số CMND
                If Not p.Ow_CardDate Is Nothing Then
                    txtOwCardDate.Text = CType(p.Ow_CardDate, Date).ToString("dd/MM/yyyy") 'Ngày cấp
                End If
                'Quốc tịch
                'trường hợp dữ liệu inport là chuỗi
                Dim DeptId = p.Ow_Provider_ID
                If IsNumeric(DeptId) Then 'kiểm tra number hay string
                    If Not p.Ow_Provider_ID Is Nothing AndAlso p.Ow_Provider_ID <> "" Then
                        ddlDeptCertified.SelectedValue = p.Ow_Provider_ID
                    End If
                Else
                    Dim _joinDeptCertified = (From k In _data.DeptIdentifies Where k.Name = DeptId Select k).FirstOrDefault
                    If Not _joinDeptCertified Is Nothing Then
                        ddlDeptCertified.SelectedValue = _joinDeptCertified.Name
                    End If

                End If
                'giay to khac
                If Not p.Ow_Doc_ID Is Nothing AndAlso p.Ow_Doc_ID <> "" Then
                    ddlOthersPaper.SelectedValue = p.Ow_Doc_ID 'Giấy tờ khác
                Else
                    ddlOthersPaper.Items.Clear()

                End If

                txtOtherPaperCode.Text = IIf(IsNothing(p.Ow_DocCode) = True, "", p.Ow_DocCode) 'Mã số

                If Not p.Ow_DocDate Is Nothing AndAlso p.Ow_DocDate <> "01/01/1900" Then
                    txtOthersPaperDateIssue.Text = CType(p.Ow_DocDate, Date).ToString("dd/MM/yyyy") 'Ngày cấp
                End If

                If Not p.Ow_DocOffiCertifiedID Is Nothing AndAlso p.Ow_DocOffiCertifiedID <> "" Then
                    ddlOthersPaper_NoiCap.SelectedValue = p.Ow_DocOffiCertifiedID 'Nơi cấp
                End If


                ''Thông tin hộ kinh doanh: 
                txtBizName.Text = IIf(IsNothing(p.Biz_VietName) = True, "", p.Biz_VietName) 'Tên hộ kinh doanh
                txtOw_Tel.Text = IIf(IsNothing(p.Ow_Tel) = True, "", p.Ow_Tel) 'điện thoai
                txtOw_Fax.Text = IIf(IsNothing(p.Ow_Fax) = True, "", p.Ow_Fax) 'fax
                txtOw_Email.Text = IIf(IsNothing(p.Ow_Email) = True, "", p.Ow_Email) 'Email
                txtOw_WebSite.Text = IIf(IsNothing(p.Ow_WebSite) = True, "", p.Ow_WebSite) 'Website

                p.Biz_Tel = txtOw_Tel.Text.Trim() 'điện thoai
                p.Biz_Fax = txtOw_Fax.Text.Trim() 'fax
                p.Biz_Email = txtOw_Email.Text.Trim() 'Email
                p.Biz_Website = txtOw_WebSite.Text.Trim() 'Website
                'nganh nghe kinh doanh và linh vưc
                ' p.NganhNgheKinhDoanh = ddlNganhNgheKinhDoanh.SelectedValue 'ngành nghề kinh doanh
                If Not p.LinhVucKinhDoanh Is Nothing AndAlso p.LinhVucKinhDoanh <> "" Then
                    ddlBusinessField.SelectedValue = p.LinhVucKinhDoanh 'Lĩnh vực kinh doanh
                End If
                txtVonTienMat.Text = IIf(IsNothing(p.VonTienMat) = True, 0, p.VonTienMat) 'Von tien mat
                txtVonTaiSan.Text = IIf(IsNothing(p.VonTaiSan) = True, 0, p.VonTaiSan) 'Von tai san
                If Not p.Biz_InvestCapital Is Nothing Then
                    txtBiz_InvestCapital.Text = FormatCurrency(p.Biz_InvestCapital).Replace(",", ".")  'vốn kinh doanh
                End If


                txtBiz_WordsMoney.Text = IIf(IsNothing(p.Biz_WordsMoney) = True, "", p.Biz_WordsMoney) 'Tiền viết bằng chữ
                txtMoney_string.Text = IIf(IsNothing(p.Biz_WordsMoney) = True, "", p.Biz_WordsMoney) 'Tiền viết bằng chữ hidden
                'Địa chỉ phường xa huyên
                'thuong trú
                Dim _jth = (From q In _data.CertifiedHouseholdAddresses Where q.CertifiedID = hidID.Value And q.TypeId = LoaiDiaChi.ThuongTru Select q).FirstOrDefault
                If Not _jth Is Nothing Then

                    txtDiaChiHoKhau.Text = _jth.Adress
                    ddlTinhHoKhau.SelectedValue = _jth.TinhId
                    Dim _Huyen = (From q In _data.Provinces Where q.ParentId = _jth.TinhId Order By q.Title Select q.Id, q.Code, q.Title).ToList
                    With ddlHuyenHoKhau
                        .DataSource = _Huyen
                        .DataValueField = "Id"
                        .DataTextField = "Title"
                        .DataBind()
                        .Items.Add(New ListItem("--- Chọn ---", 0))
                    End With
                    ddlHuyenHoKhau.SelectedValue = _jth.HuyenId
                    Dim _PhuongXa = (From q In _data.Provinces Where q.ParentId = _jth.HuyenId Order By q.Title Select q.Id, q.Code, q.Title).ToList
                    With ddlXaThiTranHoKhau
                        .DataSource = _PhuongXa
                        .DataValueField = "Id"
                        .DataTextField = "Title"
                        .DataBind()
                        .Items.Add(New ListItem("--- Chọn ---", 0))
                    End With
                    ddlXaThiTranHoKhau.SelectedValue = _jth.XaThiTranId
                    hidHuyenHoKhau.Text = _jth.HuyenId
                    hidXaThiTranHoKhau.Text = _jth.XaThiTranId

                End If
                'tam trú
                Dim _jtr = (From q In _data.CertifiedHouseholdAddresses Where q.CertifiedID = hidID.Value And q.TypeId = LoaiDiaChi.TamTru Select q).FirstOrDefault
                If Not _jtr Is Nothing Then
                    txtDiaChiHienTai.Text = _jtr.Adress
                    ddlTinhHienTai.SelectedValue = _jtr.TinhId

                    Dim _Huyen = (From q In _data.Provinces Where q.ParentId = _jtr.TinhId Order By q.Title Select q.Id, q.Code, q.Title).ToList
                    With ddlHuyenHienTai
                        .DataSource = _Huyen
                        .DataValueField = "Id"
                        .DataTextField = "Title"
                        .DataBind()
                        .Items.Add(New ListItem("--- Chọn ---", 0))
                    End With
                    ddlHuyenHienTai.SelectedValue = _jtr.HuyenId


                    Dim _PhuongXa = (From q In _data.Provinces Where q.ParentId = _jtr.HuyenId Order By q.Title Select q.Id, q.Code, q.Title).ToList
                    With ddlXaThiTranHienTai
                        .DataSource = _PhuongXa
                        .DataValueField = "Id"
                        .DataTextField = "Title"
                        .DataBind()
                        .Items.Add(New ListItem("--- Chọn ---", 0))
                    End With
                    ddlXaThiTranHienTai.SelectedValue = _jtr.XaThiTranId

                    hidHuyenHienTai.Text = _jtr.HuyenId
                    hidXaThiTranHienTai.Text = _jtr.XaThiTranId

                End If
                'đia điểm kinh doanh
                Dim _jdd = (From q In _data.CertifiedHouseholdAddresses Where q.CertifiedID = hidID.Value And q.TypeId = LoaiDiaChi.DiaDiemKinhDoanh Select q).FirstOrDefault
                If Not _jdd Is Nothing Then
                    txtBiz_HeadOffice.Text = _jdd.Adress
                    ddlTinhDiaDiemKD.SelectedValue = _jdd.TinhId

                    Dim _Huyen = (From q In _data.Provinces Where q.ParentId = _jdd.TinhId Order By q.Title Select q.Id, q.Code, q.Title).ToList
                    With ddlHuyenDiaDiemKD
                        .DataSource = _Huyen
                        .DataValueField = "Id"
                        .DataTextField = "Title"
                        .DataBind()
                        .Items.Add(New ListItem("--- Chọn ---", 0))
                    End With
                    ddlHuyenDiaDiemKD.SelectedValue = _jdd.HuyenId


                    Dim _PhuongXa = (From q In _data.Provinces Where q.ParentId = _jdd.HuyenId Order By q.Title Select q.Id, q.Code, q.Title).ToList
                    With ddlXaThiTranDiaDiemKD
                        .DataSource = _PhuongXa
                        .DataValueField = "Id"
                        .DataTextField = "Title"
                        .DataBind()
                        .Items.Add(New ListItem("--- Chọn ---", 0))
                    End With
                    hidHuyenDiaDiemKD.Text = _jdd.HuyenId
                    hidXaThiTranDiaDiemKD.Text = _jdd.XaThiTranId
                End If

            End If
        End Using
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Using data As New VSEntities
            'so sanh tren code cua GCN 
            Dim MaGCN As String = (From q In data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q.CertifiedCode).FirstOrDefault
            Dim checkCode As String = Nothing
            If Not chkBangHieu.Checked Then
                checkCode = (From q In data.CertifiedHouseholds Where q.Biz_VietName = txtBizName.Text.Trim() And q.CertifiedCode <> MaGCN  And q.ProvinceId = hidCurHuyenId.Value Select q.Ow_Name).FirstOrDefault
            End If

            If Not checkCode Is Nothing Then
                Excute_Javascript("Alertbox('Tên hộ kinh doanh đã tồn tại trong hệ thống.')", Me.Page, True)
                Exit Sub
            End If
            Dim p As New VSModel.CertifiedHousehold
            Try

                'Thông tin chung
                p.CertifiedCode = MaGCN ' add GCN cũ

                p.CertifiedStatus = "D" 'cấp mới
                Dim _checkUptime = (From q In data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Order By q.CertifiedUp_Time Descending Select q.CertifiedUp_Time).FirstOrDefault
                p.CertifiedUp_Time = _checkUptime + 1
                p.CertifiedUp_Date = Now 'ngay nhap ho so
                'thong tin ca nhan
                p.Ow_Name = txtOwRepresentative.Text 'Họ tên
                p.Ow_Sex = rdlSex.SelectedValue 'giới tính
                p.Ow_BirthDate = txtOwDateOfBirth.Text 'ngày tháng năm sinh
                p.Ow_National_ID = ddlCitizen.Text 'dân tộc
                p.Ow_Nationality_ID = ddlCountry.Text 'Quốc tịch


                p.Ow_CardID = txtOwCardId.Text 'Số CMND
                p.Ow_CardDate = StringToDate(txtOwCardDate.Text) 'Ngày cấp
                p.Ow_Provider_ID = ddlDeptCertified.Text 'Nơi cấp

                'giay to khac
                p.Ow_Doc_ID = ddlOthersPaper.SelectedValue 'Giấy tờ khác
                p.Ow_DocCode = txtOtherPaperCode.Text 'Mã số
                p.Ow_DocDate = StringToDate(txtOthersPaperDateIssue.Text.Trim()) 'Ngày cấp

                p.Ow_DocOffiCertifiedID = ddlOthersPaper_NoiCap.Text 'Nơi cấp

                'Thông tin hộ kinh doanh: 
                p.Biz_VietName = txtBizName.Text.Trim() 'Tên hộ kinh doanh
                p.Ow_Tel = txtOw_Tel.Text.Trim() 'điện thoai
                p.Ow_Fax = txtOw_Fax.Text.Trim() 'fax
                p.Ow_Email = txtOw_Email.Text.Trim() 'Email
                p.Ow_WebSite = txtOw_WebSite.Text.Trim() 'Website

                p.Biz_Tel = txtOw_Tel.Text.Trim() 'điện thoai
                p.Biz_Fax = txtOw_Fax.Text.Trim() 'fax
                p.Biz_Email = txtOw_Email.Text.Trim() 'Email
                p.Biz_Website = txtOw_WebSite.Text.Trim() 'Website
                'nganh nghe kinh doanh và linh vưc
                ' p.NganhNgheKinhDoanh = ddlNganhNgheKinhDoanh.SelectedValue 'ngành nghề kinh doanh
                p.LinhVucKinhDoanh = ddlBusinessField.Text 'Lĩnh vực kinh doanh
                p.VonTienMat = txtVonTienMat.Text.Trim
                p.VonTaiSan = txtVonTaiSan.Text.Trim
                p.Biz_InvestCapital = txtBiz_InvestCapital.Text.Trim().Replace(".", "") 'vốn kinh doanh
                p.Biz_WordsMoney = txtMoney_string.Text.Trim() 'Tiền viết bằng chữ

                p.Created = Now
                p.Creator = Session("UserName")
                Dim _StatusId As String = TinhTrangHoSo.Nhap
                If Not _StatusId Is Nothing Then
                    p.StatusId = TinhTrangHoSo.Nhap ' de duyet tai lieu
                Else
                    p.StatusId = 1
                End If
                p.NguonTao = NguonTao.MotCua
                p.ProvinceId = hidHuyenDiaDiemKD.Text ' Huyên đang ký kinh doanh
                Dim _ParentId As Integer = (From q In data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q.ParentId).FirstOrDefault
                p.ParentId = _ParentId ' parentId ho so da tim duoc
                'luu thong tin bien nhan 
                Dim _HuyenObj = (From q In data.Provinces Where q.Id = hidCurHuyenId.Value Select q).FirstOrDefault
                If Not _HuyenObj Is Nothing Then
                    Dim _SoNgayTraHoSo As Integer
                    If StringToDateTime(Now.ToString("dd/MM/yyyy"), _HuyenObj.GioBienNhan) > Now Then
                        _SoNgayTraHoSo = _HuyenObj.SoNgayTraHoSo - 1
                    Else
                        _SoNgayTraHoSo = _HuyenObj.SoNgayTraHoSo
                    End If
                    p.NgayTraHoSo = data.uspGetNumDateDelivery(Now.Date, _SoNgayTraHoSo).FirstOrDefault.DeliveryDate
                End If


                data.CertifiedHouseholds.AddObject(p)
                Dim strGCN As String = ""
                If Not p.CertifiedCode Is Nothing Then
                    strGCN = p.CertifiedCode
                End If
                Dim strLog As String = "Giay CN:" & strGCN & ", tên hộ: " & p.Biz_VietName & ", nguoi dai dien: " & p.Ow_Name & ", CMND: " & p.Ow_CardID _
                                       & ", địa chỉ kinh doanh: " & p.Biz_HeadOffice
                Insert_App_Log("Tạo  Certified:" & strLog & "", Function_Name.CertifiedHousehold, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                data.SaveChanges()
                'Địa chỉ phường xa huyên
                Dim tht As New VSModel.CertifiedHouseholdAddress
                'thường trú
                tht.CertifiedID = p.CertifiedID
                tht.TypeId = LoaiDiaChi.ThuongTru
                tht.Adress = txtDiaChiHoKhau.Text.Trim()
                tht.TinhId = ddlTinhHoKhau.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                tht.HuyenId = hidHuyenHoKhau.Text
                tht.XaThiTranId = hidXaThiTranHoKhau.Text
                data.CertifiedHouseholdAddresses.AddObject(tht)
                data.SaveChanges()
                'luu thuong tru vao CertifiedHousehold
                'lay tien cac truong theo value
                'xa
                Dim jx = (From q In data.Provinces Where q.Id = hidXaThiTranHoKhau.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jh = (From q In data.Provinces Where q.Id = hidHuyenHoKhau.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jt = (From q In data.Provinces Where q.Id = ddlTinhHoKhau.SelectedValue Select q.Title).FirstOrDefault
                p.Ow_Resident = txtDiaChiHoKhau.Text.Trim() & ", " & jx & ", " & jh & ", " & jt
                data.SaveChanges()
                'tam trú
                Dim tt As New VSModel.CertifiedHouseholdAddress
                tt.CertifiedID = p.CertifiedID
                tt.TypeId = LoaiDiaChi.TamTru
                tt.Adress = txtDiaChiHienTai.Text.Trim()
                tt.TinhId = ddlTinhHienTai.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                tt.HuyenId = hidHuyenHienTai.Text
                tt.XaThiTranId = hidXaThiTranHienTai.Text
                data.CertifiedHouseholdAddresses.AddObject(tt)
                data.SaveChanges()
                'luu tam tru vao certifiedhousehold
                'lay tien cac truong theo value
                'xa
                Dim jxt = (From q In data.Provinces Where q.Id = hidXaThiTranHienTai.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jht = (From q In data.Provinces Where q.Id = hidHuyenHienTai.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jtt = (From q In data.Provinces Where q.Id = ddlTinhHienTai.SelectedValue Select q.Title).FirstOrDefault
                p.Ow_Present = txtDiaChiHienTai.Text.Trim() & ", " & jxt & ", " & jht & ", " & jtt
                p.XaPhuongId = hidXaThiTranDiaDiemKD.Text ' luu XaPhuongId de report

                'địa điểm kinh doanh
                Dim kd As New VSModel.CertifiedHouseholdAddress
                kd.CertifiedID = p.CertifiedID
                kd.TypeId = LoaiDiaChi.DiaDiemKinhDoanh
                kd.Adress = txtBiz_HeadOffice.Text.Trim()
                kd.TinhId = ddlTinhDiaDiemKD.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                kd.HuyenId = hidHuyenDiaDiemKD.Text
                kd.XaThiTranId = hidXaThiTranDiaDiemKD.Text
                data.CertifiedHouseholdAddresses.AddObject(kd)
                data.SaveChanges()
                'luu dia diem kinh doanh vao certifiedhousehold
                'lay tien cac truong theo value
                'xa
                Dim jxd = (From q In data.Provinces Where q.Id = hidXaThiTranDiaDiemKD.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jhd = (From q In data.Provinces Where q.Id = hidHuyenDiaDiemKD.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jtd = (From q In data.Provinces Where q.Id = ddlTinhDiaDiemKD.SelectedValue Select q.Title).FirstOrDefault
                p.Biz_HeadOffice = txtBiz_HeadOffice.Text.Trim() & ", " & jxd & ", " & jhd & ", " & jtd
                'start ngành nghề

                'xoa thong tin nganh nghe ttuoc khi luu
                'Dim _jng = (From q In data.CertifiedHouseholdNganhNghes Where q.CertifiedID = hidID.Value Select q).ToList
                'For Each _i In _jng
                '    data.CertifiedHouseholdNganhNghes.DeleteObject(_i)
                'Next
                'data.SaveChanges()
                'lưu thông tin cho CertifiedHouseholdNganhNghe
                Try
                    Dim index As Integer = 0
                    Dim GrossAmount As Integer = 0
                    For i As Integer = 0 To hidRowIndex.Value - 1
                        Dim strMaterialCode As String = ""
                        Dim strMaterialDescription As String = ""
                        Dim strUnit As String = ""
                        Dim intAmount As Integer = 0

                        Dim txtMaterialCode As String = "txtChoice" + i.ToString
                        If Request.Form(txtMaterialCode) <> Nothing AndAlso Request.Form(txtMaterialCode).ToString.Trim() <> "" Then
                            strMaterialCode = Request.Form(txtMaterialCode)
                        End If

                        Dim txtMaterialDescription As String = "txtDescription" + i.ToString
                        If Request.Form(txtMaterialDescription) <> Nothing AndAlso Request.Form(txtMaterialDescription).ToString.Trim() <> "" Then
                            strMaterialDescription = Request.Form(txtMaterialDescription)
                        End If

                        If (strMaterialCode.Trim <> "") Then
                            Dim _NganhNgheId As Integer = (From q In data.DanhMucNganhNghes Where q.Code = strMaterialCode Select q.Id).FirstOrDefault

                            Dim NganhNgheList As New CertifiedHouseholdNganhNghe
                            NganhNgheList.CertifiedID = p.CertifiedID
                            NganhNgheList.DanhMucNganhNgheID = _NganhNgheId
                            NganhNgheList.Description = strMaterialDescription

                            data.CertifiedHouseholdNganhNghes.AddObject(NganhNgheList)

                            data.SaveChanges()
                            index = index + 1

                            'End If
                        End If

                        ' luu thong tin vao nganh nghe kinh doanh de hien thi
                        'lấy danh sách chi tiết ngành nghề trong CertifiedHouseholdNganhNghes theo P.CertifiedID vừa tạo cấp đổi
                        Dim strNganhNghe As String = ""
                        Dim _nn = (From q In data.CertifiedHouseholdNganhNghes Where q.CertifiedID = p.CertifiedID Select q).ToList
                        For Each a In _nn
                            Dim nganhnghe = (From k In data.DanhMucNganhNghes Where k.Id = a.DanhMucNganhNgheID Select k).FirstOrDefault
                            If Not a.Description Is Nothing AndAlso a.Description <> "" Then
                                strNganhNghe = strNganhNghe & a.Description & " (" & nganhnghe.Code & ")" & ", "
                            Else
                                strNganhNghe = strNganhNghe & nganhnghe.Name & " (" & nganhnghe.Code & ")" & ", "
                            End If
                        Next
                        p.NganhNgheKinhDoanh = strNganhNghe

                    Next
                Catch ex As Exception
                    Excute_Javascript("Alertbox('Cập nhật ngành nghề thất bại.');", Me.Page, True)
                    Exit Sub
                End Try
                'end ngành nghề
                ''Xoa di danh sach ca nhan gop von
                'Dim _sql = "DELETE FROM CertifiedHouseHoldMember WHERE CertifiedID= " & hidID.Value
                'data.ExecuteStoreCommand(_sql)
                'start danh sách góp vốn

                'lưu thông tin cho CertifiedHouseholdMember
                Try
                    For i As Integer = 0 To hidRowIndex1.Value - 1
                        Dim strTenTV As String = ""
                        Dim strNoiDKHK As String = ""
                        Dim strVonGop As String = ""
                        Dim strTyLeVonGop As String = ""
                        Dim strCMND As String = ""
                        Dim strDescription As String = ""

                        Dim txtTenTV As String = "txtTenTV__" + i.ToString
                        If Request.Form(txtTenTV) <> Nothing AndAlso Request.Form(txtTenTV).ToString.Trim() <> "" Then
                            strTenTV = Request.Form(txtTenTV)
                        End If

                        Dim txtNoiDKHK As String = "txtNoiDKHK__" + i.ToString
                        If Request.Form(txtNoiDKHK) <> Nothing AndAlso Request.Form(txtNoiDKHK).ToString.Trim() <> "" Then
                            strNoiDKHK = Request.Form(txtNoiDKHK)
                        End If
                        Dim txtVonGop As String = "txtVonGop__" + i.ToString
                        If Request.Form(txtTenTV) <> Nothing AndAlso Request.Form(txtVonGop).ToString.Trim() <> "" Then
                            strVonGop = Request.Form(txtVonGop)
                        End If

                        Dim txtTyLeVonGop As String = "txtTyLeVonGop__" + i.ToString
                        If Request.Form(txtTyLeVonGop) <> Nothing AndAlso Request.Form(txtTyLeVonGop).ToString.Trim() <> "" Then
                            strTyLeVonGop = Request.Form(txtTyLeVonGop)
                        End If
                        Dim txtCMND As String = "txtCMND__" + i.ToString
                        If Request.Form(txtCMND) <> Nothing AndAlso Request.Form(txtCMND).ToString.Trim() <> "" Then
                            strCMND = Request.Form(txtCMND)
                        End If

                        Dim txtDescription As String = "txtDescription__" + i.ToString
                        If Request.Form(txtDescription) <> Nothing AndAlso Request.Form(txtDescription).ToString.Trim() <> "" Then
                            strDescription = Request.Form(txtDescription)
                        End If

                        If (strTenTV.Trim <> "") Then

                            Dim member As New CertifiedHouseholdMember
                            member.CertifiedID = p.CertifiedID
                            member.MemberName = strTenTV
                            member.MemberAddress = strNoiDKHK
                            member.MemberValues = strVonGop
                            member.MemberRate = strTyLeVonGop
                            member.MemberCard = strCMND
                            member.MemberDes = strDescription
                            member.MemberOrder = member.Id
                            data.CertifiedHouseholdMembers.AddObject(member)

                            data.SaveChanges()

                            'End If
                        End If
                    Next
                Catch ex As Exception
                    Excute_Javascript("Alertbox('Cập nhật danh sách góp vốn thất bại.');", Me.Page, True)
                    Exit Sub
                End Try
                'end danh sách góp vốn

                'start thành phần hồ sơ
                Dim intId As Integer = 0
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        'lay id cua thanh phan ho so
                        intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                        Dim ThanhPhanHoSo As New CertifiedHouseholdThanhPhanHoSo
                        ThanhPhanHoSo.CertifiedID = p.CertifiedID
                        ThanhPhanHoSo.ThanhPhanHoSoId = intId
                        data.CertifiedHouseholdThanhPhanHoSoes.AddObject(ThanhPhanHoSo)
                        data.SaveChanges()
                    End If
                Next
                'loai thay doi
                Dim _LoaiId As Integer = 0
                For Each item As GridViewRow In grdShowLoaiThayDoi.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        'lay id loai thay doi
                        _LoaiId = grdShowLoaiThayDoi.DataKeys(item.RowIndex)("Id").ToString
                        Dim LoaiThayDoi As New CertifiedHouseholdChangingType
                        LoaiThayDoi.CertifiedID = p.CertifiedID
                        LoaiThayDoi.ChangingTypeiId = _LoaiId
                        data.CertifiedHouseholdChangingTypes.AddObject(LoaiThayDoi)
                        data.SaveChanges()
                    End If
                Next
                'correct lai Province + HuyenId
                Dim _UserId As Integer = Session("UserId")
                Dim _CertifiedId As Integer = p.CertifiedID
                data.uspCertifiedHouseHouseUpdate(_UserId, _CertifiedId)
                Excute_Javascript("Alertbox('Thêm mới dữ liệu thành công.');window.location ='../../Page/TiepNhan/Detail.aspx?Certifiedid=" & p.CertifiedID & "';", Me.Page, True)

            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/TiepNhan/List.aspx';", Me.Page, True)
            End Try

        End Using
    End Sub
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound

        Using _data As New VSEntities
            If e.Row.RowIndex >= 0 Then
                Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
                lblSTT.Text = e.Row.RowIndex + 1
                'lay thanh phan ho so 
                Dim _j = (From q In _data.CertifiedHouseholdThanhPhanHoSoes Where q.CertifiedID = hidID.Value Select q.ThanhPhanHoSoId).ToArray
                If Not _j Is Nothing Then
                    Dim chkItem As CheckBox = e.Row.FindControl("chkItem")
                    'kiem tra id cua item co trong tphoso hay ko? neu co thi check ko thi uncheck
                    Dim curId As Integer = grdShow.DataKeys(e.Row.RowIndex)("Id")
                    If Not grdShow.DataKeys(e.Row.RowIndex)("Id") Is Nothing AndAlso _j.Contains(curId) Then
                        chkItem.Checked = 1
                    End If

                End If
            End If
        End Using
    End Sub
    'Protected Sub grdShowLoaiThayDoi_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShowLoaiThayDoi.RowDataBound
    '    Using _data As New VSEntities
    '        If e.Row.RowIndex >= 0 Then
    '            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
    '            lblSTT.Text = e.Row.RowIndex + 1
    '            'lay loai thay doi
    '            Dim _j = (From q In _data.CertifiedHouseholdChangingTypes Where q.CertifiedID = hidID.Value Select q.ChangingTypeiId).ToArray
    '            If Not _j Is Nothing Then
    '                Dim chkItem As CheckBox = e.Row.FindControl("chkItem")
    '                'kiem tra id cua item co trong loai thay doi hay ko? neu co thi check ko thi uncheck
    '                Dim curId As Integer = grdShowLoaiThayDoi.DataKeys(e.Row.RowIndex)("Id")
    '                If Not grdShowLoaiThayDoi.DataKeys(e.Row.RowIndex)("Id") Is Nothing AndAlso _j.Contains(curId) Then
    '                    chkItem.Checked = 1
    '                End If

    '            End If
    '        End If
    '    End Using
    'End Sub
End Class

